/**
 * Copyright (C), 2020-2020, 软件公司
 * FileName: UserSreviceImpl
 * Author:   cakin
 * Date:     2020/5/6
 * Description: 用户服务实现
 */
package com.cakin.newssystem.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cakin.newssystem.common.RequestException;
import com.cakin.newssystem.common.ResponseCode;
import com.cakin.newssystem.core.dto.SignInDTO;
import com.cakin.newssystem.core.entity.User;
import com.cakin.newssystem.core.mapper.UserMapper;
import com.cakin.newssystem.core.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;


/**
 * @ClassName: UserSreviceImpl
 * @Description: 用户服务实现
 * @Date: 2020/5/6
 * @Author: cakin
 */
@Service
@Transactional
@Slf4j
public class UserSreviceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    /**
     * 数据访问
     */
    @Autowired
    private UserMapper userMapper;

    @Override
    public void signIn( SignInDTO signInDTO ) {
        if (StringUtils.isEmpty(signInDTO.getUsername()) || StringUtils.isEmpty(signInDTO.getPassword())) {
            throw new RequestException(ResponseCode.SING_IN_INPUT_EMPTY);
        }

        /**
         * 加密算法：MD5
         */
        LambdaQueryWrapper<User> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(User::getUsername, signInDTO.getUsername()).
                eq(User::getPassword, DigestUtils.md5Hex(signInDTO.getPassword()));

        List<User> userList = userMapper.selectList(lambdaQueryWrapper);
        if (userList.size() != 1) {
            throw new RequestException(ResponseCode.SIGN_IN_INPUT_FAIL);
        }
    }

    @Override
    public void reg( SignInDTO signInDTO ) {
        // 非空判断
        if (StringUtils.isEmpty(signInDTO.getUsername()) || StringUtils.isEmpty(signInDTO.getPassword())) {
            throw new RequestException(ResponseCode.SING_IN_INPUT_EMPTY);
        }
        // 检查是否已注册
        List<User> list = this.list(Wrappers.<User>lambdaQuery().eq(User::getUsername, signInDTO.getUsername()));
        if (list.size() > 0) {
            throw new RequestException(ResponseCode.HAVE_REG);
        }
        // 保存
        User user = new User();
        user.setUsername(signInDTO.getUsername());
        user.setPassword(DigestUtils.md5Hex(signInDTO.getPassword()));
        this.save(user);
    }
}
